package com.bobo.serviceorder.lock;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

/**
 * @author bobo
 * @date 2021-04-19
 */

public class ZookeeperLockTest {
    ZooKeeper zk;

    @Before
    public void conn() throws IOException {
        zk = new ZooKeeper("127.0.0.1:2181", 1000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println("watchedEvent:" + watchedEvent);
            }
        });
    }

    @After
    public void close() {
        try {
            zk.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void lock() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 10; i++) {
            new Thread() {
                @Override
                public void run() {
                    ZookeeperLock zookeeperLock=new ZookeeperLock();
                    zookeeperLock.setZk(zk);
                    String threadName = Thread.currentThread().getName();
                    zookeeperLock.setThreadName(threadName);
                    //每一个线程：
                    //抢锁
                    zookeeperLock.tryLock();
                    //干活
                    System.out.println(threadName + " working...");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //释放锁
                    zookeeperLock.unLock();
                }
            }.start();
        }
        while (true) {

        }


    }
}
